﻿namespace System
{
    public static class DecimalExtension
    {
        /// <summary>四舍五入</summary>
        public static decimal Round(this Decimal @this, int decimals, MidpointRounding mode = MidpointRounding.AwayFromZero)
        => Math.Round(@this, decimals, mode);

        /// <summary>将数字转换成字符串，并去掉小数点后面无效的0</summary>
        public static string TrimEndZero(this Decimal @this)
        {
            var str = @this.ToString();
            if (str.Contains(".")) return str.TrimEnd('0').TrimEnd('.');
            return str;
        }

        /// <summary>获取小数的有效小数位数</summary>
        public static int GetDecimals(this Decimal @this)
        {
            var str = @this.TrimEndZero();
            if (str.IndexOf(".") < 1) return 0;
            return str.Length - str.IndexOf(".") - 1;
        }

        /// <summary>占比后加百分号</summary>
        public static string AppendPer(this Decimal? @this)
        {
            return @this == null ? "" : @this + "%";
        }
    }
}
